import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import {getNotificationUnRead} from './notification'
import { getUserOrganizations } from './organization'

export const getUser = user => ({
  type: 'GET_USER',
  user
})

export const initUser = () => {
  return dispatch => {
    (async () => {
      const res = await request.get('../api/users/21')
      if (res.status === HTTP_CODE.OK) {
        dispatch(getUser(res.body))
        dispatch(getNotificationUnRead(res.body.id))
        dispatch(getUserOrganizations(res.body.id))
      }
    })()
  }
}
export const updateUserCurrentOrganizationId = (data) => {
  return dispatch => {
    (async () => {
      const res = await request.update(`../api/users/${data.userId}/organizations`, data)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        dispatch(getUserById(data.userId))
      }
    })()
  }
}
export const searchUser = (value, callback) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`../api/v3/users?userName=${value}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'SEARCH_USERS',
          data: res.body
        })
        if (callback) {
          callback(res.body)
        }
      }
    })()
  }
}

export const getUserById = (id) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`../api/users/${id}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(getUser(res.body))
      }
    })()
  }
}